package com.zzyl.nursing.service.impl;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.framework.web.service.TokenService;
import com.zzyl.nursing.domain.FamilyMember;
import com.zzyl.nursing.dto.FamilyLoginDto;
import com.zzyl.nursing.mapper.FamilyMapper;
import com.zzyl.nursing.service.FamilyService;
import com.zzyl.nursing.vo.LoginVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;


@Service
@Slf4j
public class FamilyServiceImpl implements FamilyService {
    //获取openid url
    private final static String OPENID = "https://api.weixin.qq.com/sns/jscode2session";
    //获取手机号 url
    private final static String PHONE = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=";
    private final static String Token = "https://api.weixin.qq.com/cgi-bin/token";


    @Value("${wx.appid}")
    private String appid;
    @Value("${wx.secret}")
    private String secret;
    @Autowired
    private FamilyMapper familyMapper;
    @Autowired
    private TokenService tokenService;

    @Override
    public LoginVo login(FamilyLoginDto familyLoginDto) {
        //业务流程
        //1.先获取openid
        String openid = getopenId(familyLoginDto.getCode());
        //3.如果不存在则新增family数据
        LambdaQueryWrapper<FamilyMember> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(FamilyMember::getOpenId, openid);
        FamilyMember familyMember = familyMapper.selectOne(wrapper);
        //如果不存在则表示是新用户 新增用户及其手机号
        if (familyMember == null) {
            //获取手机号 插入数据
            String phoneNumber = getPhoneNumber(familyLoginDto.getPhoneCode());
            familyMember = new FamilyMember();
            familyMember.setPhone(phoneNumber);
            familyMember.setOpenId(openid);
            familyMember.setName("白茶与风");
            familyMapper.insert(familyMember);
        }
        //4 生成jwt token 封装返回给前端
        HashMap<String, Object> map = new HashMap<>();
        map.put("openid", openid);
        map.put("id", familyMember.getId());
        String token = tokenService.createToken(map);
        LoginVo loginVo = new LoginVo();
        loginVo.setNickName(familyMember.getName());
        loginVo.setToken(token);
        return loginVo;
    }

    private String getopenId(String code) {
        log.info("开始获取openid");
        HashMap<String, Object> map = new HashMap<>();
        map.put("appid", appid);
        map.put("secret", secret);
        map.put("js_code", code);
        map.put("grant_type", "authorization_code");
        String result = HttpUtil.get(OPENID, map);
        JSONObject jsonObject = JSONUtil.parseObj(result);
        log.info("获取openid结果：{}", jsonObject);
        return jsonObject.getStr("openid");
    }

    private String getPhoneNumber(String phoneCode) {
        log.info("开始获取手机号");
        HashMap<String, Object> map = new HashMap<>();
        map.put("code", phoneCode);
        String accessToken = getAccessToken();
        String response = HttpUtil.post(PHONE+accessToken, JSONUtil.toJsonStr(map));
        log.info("获取手机号结果：{}", response);
        JSON parse = JSONUtil.parse(response);
        return JSONUtil.getByPath(parse, "phone_info.phoneNumber") + "";
    }

    private String getAccessToken() {
        log.info("开始获取access_token");
        HashMap<String, Object> map = new HashMap<>();
        map.put("appid", appid);
        map.put("secret", secret);
        map.put("grant_type", "client_credential");
        String result = HttpUtil.get(Token, map);
        JSONObject jsonObject = JSONUtil.parseObj(result);
        log.info("获取access_token {}", jsonObject);
        return jsonObject.getStr("access_token");

    }
}
